package com.github.thinwonton.springboot.showcase.transaction.propagation.service.propagation_requires_new;

import com.github.thinwonton.springboot.showcase.transaction.propagation.dao.AccountDao;
import com.github.thinwonton.springboot.showcase.transaction.propagation.domain.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
public class AccountService {

	@Autowired
	private AccountDao accountDao;

	public void changeMoneyNoTx(Long id, BigDecimal increased) {
		Account account = accountDao.selectByPrimaryKey(id);
		account.setMoney(account.getMoney().add(increased));
		accountDao.updateByPrimaryKeySelective(account);
	}

	@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
	public void changeMoney(Long id, BigDecimal increased) {
		Account account = accountDao.selectByPrimaryKey(id);
		account.setMoney(account.getMoney().add(increased));
		accountDao.updateByPrimaryKeySelective(account);
	}

	@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
	public void changeMoneyThrowException(Long id, BigDecimal increased) {
		Account account = accountDao.selectByPrimaryKey(id);
		account.setMoney(account.getMoney().add(increased));
		accountDao.updateByPrimaryKeySelective(account);
		throw new RuntimeException();
	}
}
